package com.cocolove2.andbase.http;

import android.text.TextUtils;

import com.cocolove2.andbase.ApiHelper;
import com.cocolove2.andbase.ApiService2;
import com.cocolove2.andbase.BasePresenter;
import com.cocolove2.andbase.MyApplication;
import com.cocolove2.andbase.bean.BaseResponse;
import com.cocolove2.andbase.bean.Weather;
import com.cocolover2.andbase.http.OnHttpListener;
import com.cocolover2.andbase.http.api.ABaseApi;
import com.cocolover2.andbase.utils.FileUtil;
import com.cocolover2.andbase.utils.log.KLog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 天气测试接口有次数限制
 */
public class HttpTestPresenter extends BasePresenter<IHttpView> {

    public void getBaidu() {
        Disposable disposable = ApiHelper.getInstance().sendRequest(new ABaseApi.OnObservableListener<ResponseBody>() {
            @Override
            public Observable<ResponseBody> onObservable() {
                return ApiHelper.getInstance().getApiService().getBaidu();
            }
        }, new OnHttpListener<ResponseBody>() {
            @Override
            public void onSuccess(ResponseBody response) {
                if (isViewAttached()) {
                    try {
                        getView().onBaiduResult(response.string(), 0, "请求成功");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                if (isViewAttached()) {
                    getView().onBaiduResult("", code, msg);
                }
            }
        });

        addCompositeDisposable(disposable);
    }


    public void getBaidu2() {
        Disposable disposable = ApiHelper.getInstance().sendRequest(new ABaseApi.OnObservableListener<ResponseBody>() {
            @Override
            public Observable<ResponseBody> onObservable() {
                return ApiHelper.getInstance().getApiService(ApiService2.class).getBaidu();
            }
        }, new OnHttpListener<ResponseBody>() {
            @Override
            public void onSuccess(ResponseBody response) {
                if (isViewAttached()) {
                    try {
                        getView().onBaiduResult(response.string(), 0, "请求成功");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                if (isViewAttached()) {
                    getView().onBaiduResult("", code, msg);
                }
            }
        });

        addCompositeDisposable(disposable);
    }



    public void getWeather() {
        Disposable disposable = getApiHelper().sendRequest(new ABaseApi.OnObservableListener<BaseResponse<Weather>>() {
            @Override
            public Observable<BaseResponse<Weather>> onObservable() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("cityname", "厦门");
                params.put("key", "64064052963e1505b824055d521e1ea9");
                params.put("format", "2");
                return getApiHelper().getApiService().getWeather(params);
            }
        }, new OnHttpListener<BaseResponse<Weather>>() {
            @Override
            public void onSuccess(BaseResponse<Weather> response) {
                if (isViewAttached()) {
                    getView().onWeatherInfo(response.getData(), response.getCode(), response.getMessage());
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                if (isViewAttached()) {
                    getView().onWeatherInfo(null, code, msg);
                }
            }
        });

        addCompositeDisposable(disposable);
    }

    public void getWeather2() {
        Disposable disposable = getApiHelper().sendRequest(new ABaseApi.OnObservableListener<ResponseBody>() {
            @Override
            public Observable<ResponseBody> onObservable() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("cityname", "厦门");
                params.put("key", "64064052963e1505b824055d521e1ea9");
                params.put("format", "2");
                return getApiHelper().getApiService().getWeather2(params);
            }
        }, new OnHttpListener<ResponseBody>() {
            @Override
            public void onSuccess(ResponseBody response) {
                try {
                    String str = response.string();
                    if (isViewAttached()) {
                        BaseResponse<Weather> tmp = new Gson().fromJson(str, new TypeToken<BaseResponse<Weather>>() {
                        }.getType());
                        getView().onWeatherInfo(tmp.getData(), tmp.getCode(), tmp.getMessage());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int code, String msg) {
                if (isViewAttached()) {
                    getView().onWeatherInfo(null, code, msg);
                }
            }
        });

        addCompositeDisposable(disposable);
    }


    public Call downloadFile(final String url) {
        return getApiHelper().downloadFile(url, new OnHttpListener<Response>() {
            @Override
            public void onSuccess(Response response) {
                String[] strings = url.split("/");
                String fileName = "";
                if (strings.length > 0) {
                    fileName = strings[strings.length - 1];
                }
                if (TextUtils.isEmpty(fileName)) {
                    KLog.e("下载地址不正确");
                    return;
                }
                try {
                    ResponseBody body = response.body();
                    if (body != null) {
                        String filePath = FileUtil.getCacheDir(MyApplication.getContext(), "cache").getAbsolutePath() + "/" + fileName;
                        String path = FileUtil.saveFileToDisk(body.bytes(), filePath);
                        KLog.i(path);
                        if (isViewAttached()) {
                            KLog.i(Thread.currentThread().getName() + "下载成功");
                            getView().onDownloadInfo(path, 0, "下载成功");
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onDownloadProgress(long totalBytesRead, long totalLength, int progress) {
                KLog.i(Thread.currentThread().getName() + "-->下载进度" + totalBytesRead + "#" + totalLength + "#" + progress + "%");
            }

            @Override
            public void onFailure(int code, String msg) {
                KLog.e("下载失败：" + code + "#" + msg);
                if (isViewAttached()) {
                    getView().onDownloadInfo("", code, msg);
                }
            }
        });
    }

    /**
     * 多文件上传
     *
     * @param url
     * @param params 支持file和file[]
     * @return
     */
    public Call uploadFiles(String url, Map<String, Object> params) {
        return getApiHelper().uploadFiles(url, params, new OnHttpListener<String>() {
            @Override
            public void onSuccess(String response) {
                KLog.i(Thread.currentThread().getName() + "===上传成功：" + response);
                if (isViewAttached()) {
                    getView().onUploadInfo(response, 0, "上传成功");
                }
            }

            @Override
            public void onUploadProgress(long bytesWritten, long contentLength, long speed) {

                KLog.i("上传进度" + bytesWritten + "#" + contentLength + "#" + (bytesWritten * 100 / contentLength) + "%" + "#" + speed);
            }

            @Override
            public void onFailure(int code, String msg) {
                KLog.e("上传失败：" + code + "#" + msg);
                if (isViewAttached()) {
                    getView().onUploadInfo(null, code, msg);
                }
            }
        });
    }
}
